﻿import mx.utils.Delegate;
import kliment.display.Sprite;
/**
 * ...
 * @author	Kliment
 * @version	1.5.9
 */
class kliment.display.SpriteBtn extends Sprite {
	private var _CLASS_NAME:String = 'SpriteBtn';
	static private var _EVENTS:Array = ['onRollOver', 'onRollOut', 'onRelease', 'onReleaseOutside', 'onPress', 'onDragOver', 'onDragOut', 'onMouseMove', 'onEnterFrame', 'onMouseDown', 'onMouseUp'];
	private var _addListener2:Function;
	private var _listeners:Array;
	private var _hit_mc:MovieClip;
	private var _eventTarget_mc:MovieClip;
	private var _class_instance;
	private var _enable:Boolean = true;
	private var _oldButtonMode:Boolean;
	
	public function SpriteBtn(target_mc:MovieClip, isParent:Boolean, ignoreListener:Boolean) {
		super(target_mc, isParent);
		AsBroadcaster.initialize(this);
		
		_hit_mc = _target_mc.hit_mc;
		
		_addListener2 = addListener;
		addListener = Delegate.create(this, _addListener);
		
		if (!ignoreListener)
			delegateListener(this);
	}
	
	private function _addListener(target:Object):Void {
		_addListener2(target);
		
		for (var i in _EVENTS) 
			_checkEvent(_EVENTS[i], target);
	}
	
	public function get buttonMode():Boolean { return _target_mc.useHandCursor }
	public function set buttonMode(value:Boolean):Void { _target_mc.useHandCursor = value }
	
	public function get enable():Boolean { return _enable; }
	public function set enable(value:Boolean):Void {
		if (_enable != value) {
			if (value) {
				buttonMode = _oldButtonMode;
				delegateListener(_class_instance);
			} else {
				_oldButtonMode = buttonMode;
				buttonMode = false;
				_clearEvents(_hit_mc || _target_mc);
			}
			_enable = value;
		}
	}
	
	public function setFocus():Void { }
	public function resetFocus():Void { }
	
	public function delegateListener(class_instance):Void {
		_class_instance = class_instance;
		_clearEvents(_target_mc);
		_clearEvents(_hit_mc);
		_eventTarget_mc = _hit_mc || _target_mc;
		
		for (var i in _EVENTS) 
			_checkBroadcast(_EVENTS[i]);
	}
	
	private function _checkBroadcast(eventName:String):Void {
		for (var i in _listeners) 
			_checkEvent(eventName, _listeners[i]);
	}
	
	private function _checkEvent(eventName:String, _listener):Void {
		var this_c = this;
		if (_listener[eventName] && !_eventTarget_mc[eventName]) {
			_eventTarget_mc[eventName] = function():Void {
				this_c.broadcastMessage(eventName, this_c._class_instance);
			}
		}
	}
	
	private function _clearEvents(target_mc:MovieClip):Void {
		if (!target_mc) 
			return;
		for (var i in _EVENTS)
			delete target_mc[_EVENTS[i]];
	}
	
	private function broadcastMessage(eventName:String):Void {  }
	public function addListener(traget:Object):Void {  }
	public function removeListener(traget:Object):Void {  }
}